package com.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ConcurrentTest {
    static int count1 = 0;
    static int count2 = 0;
    static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        sync(50000);
        lock(50000);
    }

    public static void sync(int num){
        long start = System.nanoTime();
        for (int i = 0; i < num; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (ConcurrentTest.class) {
                        count1++;
                    }
                }
            }).start();
        }
        long elapsedNanos = System.nanoTime() - start;
        System.out.println("sync:" + elapsedNanos);
    }

    public static void lock(int num){
        long start = System.nanoTime();
        for (int i = 0; i < num; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    count2++;
                    lock.unlock();
                }
            }).start();
        }
        long elapsedNanos = System.nanoTime() - start;
        System.out.println("lock:" + elapsedNanos);
    }

}
